import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { finalize, forkJoin, Subject, interval, switchMap } from 'rxjs';
import { ToasterService } from '@abp/ng.theme.shared';
import { ThemeSharedModule } from '@abp/ng.theme.shared';
import { environment } from '../../environments/environment';
import { RedisCacheService, RedisStatusDto } from '../shared/services/redis-cache.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { takeUntil } from 'rxjs/operators';

interface RedisStatus {
  isEnabled: boolean;
  configuration: string;
  instanceName: string;
  status: string;
  message: string;
  usedMemory: string;
  maxMemory: string;
  connectedClients: string;
  totalCommands: string;
  cacheHitRate: string;
  totalKeys: number;
  bookStoreKeys: number;
  kehuListKeys: number;
  kehuSearchKeys: number;
  kehuAdvSearchKeys: number;
  latency: string;
  
  // 新增指标
  uptimeInDays: string;
  uptimeInSeconds: string;
  memoryFragmentationRatio: string;
  expiredKeysCount: string;
  evictedKeysCount: string;
  keyspaceHits: string;
  keyspaceMisses: string;
  rejectedConnections: string;
}

interface RedisPerformanceMetrics {
  isEnabled: boolean;
  message: string;
  benchmarkResults: {[key: string]: string};
  memoryStats: {[key: string]: string};
  commandStats: {[key: string]: number};
  setOperationsPerSecond?: number;
  getOperationsPerSecond?: number;
}

@Component({
  selector: 'app-redis-monitor',
  standalone: true,
  imports: [CommonModule, FormsModule, ThemeSharedModule],
  template: `
    <div class="card">
      <div class="card-header">
        <div class="row">
          <div class="col">
            <h5 class="card-title">Redis缓存监控</h5>
          </div>
          <div class="col text-end">
            <button class="btn btn-primary" (click)="loadRedisStatus()" [disabled]="loading">
              <i class="fa" [ngClass]="loading ? 'fa-spinner fa-spin' : 'fa-refresh'"></i>
              刷新
            </button>
          </div>
        </div>
      </div>
      
      <div class="card-body">
        <div *ngIf="loading" class="text-center my-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-2">正在获取Redis状态...</p>
        </div>
        
        <div *ngIf="!loading && redisStatus">
          <div class="alert" [ngClass]="redisStatus.isEnabled ? 'alert-success' : 'alert-warning'">
            <strong>状态: {{ redisStatus.status }}</strong> - {{ redisStatus.message }}
          </div>
          
          <div class="row mb-4">
            <div class="col-md-6">
              <div class="card">
                <div class="card-header bg-light">
                  <h6 class="mb-0">基本信息</h6>
                </div>
                <div class="card-body">
                  <table class="table table-sm">
                    <tbody>
                      <tr>
                        <th>启用状态</th>
                        <td>{{ redisStatus.isEnabled ? '已启用' : '已禁用' }}</td>
                      </tr>
                      <tr>
                        <th>连接配置</th>
                        <td>{{ redisStatus.configuration }}</td>
                      </tr>
                      <tr>
                        <th>实例名称</th>
                        <td>{{ redisStatus.instanceName }}</td>
                      </tr>
                      <tr>
                        <th>延迟</th>
                        <td>{{ redisStatus.latency }}</td>
                      </tr>
                      <tr>
                        <th>运行时间</th>
                        <td>{{ redisStatus.uptimeInDays }} 天</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
            
            <div class="col-md-6">
              <div class="card">
                <div class="card-header bg-light">
                  <h6 class="mb-0">性能指标</h6>
                </div>
                <div class="card-body">
                  <table class="table table-sm">
                    <tbody>
                      <tr>
                        <th>内存使用</th>
                        <td>{{ redisStatus.usedMemory }} / {{ redisStatus.maxMemory }}</td>
                      </tr>
                      <tr>
                        <th>连接客户端</th>
                        <td>{{ redisStatus.connectedClients }}</td>
                      </tr>
                      <tr>
                        <th>总命令数</th>
                        <td>{{ redisStatus.totalCommands }}</td>
                      </tr>
                      <tr>
                        <th>缓存命中率</th>
                        <td>{{ redisStatus.cacheHitRate }}</td>
                      </tr>
                      <tr>
                        <th>内存碎片率</th>
                        <td>{{ redisStatus.memoryFragmentationRatio }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>

          <div *ngIf="redisStatus.isEnabled && performanceMetrics" class="row mb-4">
            <div class="col-12">
              <div class="card">
                <div class="card-header bg-light d-flex justify-content-between align-items-center">
                  <h6 class="mb-0">性能指标</h6>
                  <button class="btn btn-sm btn-primary" (click)="measurePerformance()" [disabled]="isPerformanceTesting">
                    <i class="fa" [ngClass]="isPerformanceTesting ? 'fa-spinner fa-spin' : 'fa-tachometer'"></i>
                    重新测试
                  </button>
                </div>
                <div class="card-body">
                  <div class="row">
                    <div class="col-md-6 mb-3">
                      <div class="card bg-light">
                        <div class="card-body text-center">
                          <h3>{{ performanceMetrics.setOperationsPerSecond.toFixed(0) }}</h3>
                          <p class="mb-0">SET操作/秒</p>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-6 mb-3">
                      <div class="card bg-light">
                        <div class="card-body text-center">
                          <h3>{{ performanceMetrics.getOperationsPerSecond.toFixed(0) }}</h3>
                          <p class="mb-0">GET操作/秒</p>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="text-center mt-3">
                    <button class="btn btn-outline-primary btn-sm" (click)="generateTestData()" [disabled]="isGeneratingData">
                      <i class="fa" [ngClass]="isGeneratingData ? 'fa-spinner fa-spin' : 'fa-database'"></i>
                      生成测试数据 (1000条)
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="row mb-4">
            <div class="col-12">
              <div class="card">
                <div class="card-header bg-light d-flex justify-content-between align-items-center">
                  <h6 class="mb-0">键统计</h6>
                  <button class="btn btn-sm btn-danger" (click)="clearCache('BookStore:*')" [disabled]="isClearing">
                    <i class="fa" [ngClass]="isClearing ? 'fa-spinner fa-spin' : 'fa-trash'"></i>
                    清除所有BookStore缓存
                  </button>
                </div>
                <div class="card-body">
                  <div class="row">
                    <div class="col-md-3 mb-3">
                      <div class="card bg-light">
                        <div class="card-body text-center">
                          <h3>{{ redisStatus.totalKeys }}</h3>
                          <p class="mb-0">总键数</p>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-3 mb-3">
                      <div class="card bg-light">
                        <div class="card-body text-center">
                          <h3>{{ redisStatus.bookStoreKeys }}</h3>
                          <p class="mb-0">BookStore键数</p>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-3 mb-3">
                      <div class="card bg-light">
                        <div class="card-body text-center">
                          <h3>{{ redisStatus.kehuListKeys }}</h3>
                          <p class="mb-0">客户列表缓存</p>
                          <button *ngIf="redisStatus.kehuListKeys > 0" class="btn btn-sm btn-outline-danger mt-2" 
                                  (click)="clearCache('BookStore:KehuList:*')">
                            清除
                          </button>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-3 mb-3">
                      <div class="card bg-light">
                        <div class="card-body text-center">
                          <h3>{{ redisStatus.kehuSearchKeys + redisStatus.kehuAdvSearchKeys }}</h3>
                          <p class="mb-0">搜索缓存</p>
                          <button *ngIf="redisStatus.kehuSearchKeys + redisStatus.kehuAdvSearchKeys > 0" 
                                  class="btn btn-sm btn-outline-danger mt-2" 
                                  (click)="clearCache('BookStore:KehuSearch:*')">
                            清除
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                  
                  <div class="row mt-3">
                    <div class="col-md-3 mb-3">
                      <div class="card bg-light">
                        <div class="card-body text-center">
                          <h3>{{ redisStatus.expiredKeysCount || '0' }}</h3>
                          <p class="mb-0">过期键数</p>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-3 mb-3">
                      <div class="card bg-light">
                        <div class="card-body text-center">
                          <h3>{{ redisStatus.evictedKeysCount || '0' }}</h3>
                          <p class="mb-0">淘汰键数</p>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-3 mb-3">
                      <div class="card bg-light">
                        <div class="card-body text-center">
                          <h3>{{ redisStatus.keyspaceHits || '0' }}</h3>
                          <p class="mb-0">命中次数</p>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-3 mb-3">
                      <div class="card bg-light">
                        <div class="card-body text-center">
                          <h3>{{ redisStatus.keyspaceMisses || '0' }}</h3>
                          <p class="mb-0">未命中次数</p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="row">
            <div class="col-12">
              <div class="card">
                <div class="card-header bg-light">
                  <h6 class="mb-0">自定义清除缓存</h6>
                </div>
                <div class="card-body">
                  <div class="input-group">
                    <input type="text" class="form-control" [(ngModel)]="customPattern" 
                           placeholder="输入缓存键模式，例如: BookStore:KehuList:*" />
                    <button class="btn btn-danger" (click)="clearCache(customPattern)" [disabled]="!customPattern">
                      清除匹配的缓存
                    </button>
                  </div>
                  <small class="form-text text-muted">
                    使用通配符(*)匹配多个键。例如，"BookStore:KehuList:*"将匹配所有客户列表缓存。
                  </small>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div *ngIf="!loading && !redisStatus" class="alert alert-danger">
          无法获取Redis状态信息。请确保Redis服务已启动，并且配置正确。
        </div>
      </div>
    </div>
  `,
  styles: [`
    .card {
      margin-bottom: 1rem;
    }
  `]
})
export class RedisMonitorComponent implements OnInit, OnDestroy {
  redisStatus: RedisStatusDto;
  performanceMetrics: RedisPerformanceMetrics;
  loading = true;
  perfLoading = false;
  autoRefresh = false;
  refreshInterval = 30; // 刷新间隔，默认30秒
  hitRatePercentage = 0;
  memoryUsagePercentage = 0;
  clearPattern = 'BookStore:Kehu:*';
  customPattern = '';
  isClearing = false;
  isPerformanceTesting = false;
  isGeneratingData = false;
  
  private destroy$ = new Subject<void>();
  private refreshSubscription: any;

  constructor(
    private http: HttpClient,
    private toaster: ToasterService,
    private redisCacheService: RedisCacheService,
    private message: NzMessageService
  ) {}
  
  ngOnInit(): void {
    this.loadRedisStatus();
  }
  
  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
    this.stopAutoRefresh();
  }
  
  loadRedisStatus(): void {
    this.loading = true;
    this.redisCacheService.getStatus().pipe(
      takeUntil(this.destroy$)
    ).subscribe(
      status => {
        this.redisStatus = status;
        this.hitRatePercentage = this.redisCacheService.calculateHitRatePercentage(status);
        this.memoryUsagePercentage = this.redisCacheService.calculateMemoryUsagePercentage(status);
        this.loading = false;
      },
      error => {
        this.message.error('获取Redis状态失败：' + error.message);
        this.loading = false;
      }
    );
  }
  
  loadPerformanceMetrics(): void {
    this.perfLoading = true;
    this.redisCacheService.getPerformanceMetrics().pipe(
      takeUntil(this.destroy$)
    ).subscribe(
      metrics => {
        if (!metrics.setOperationsPerSecond) {
          metrics.setOperationsPerSecond = 0;
        }
        if (!metrics.getOperationsPerSecond) {
          metrics.getOperationsPerSecond = 0;
        }
        this.performanceMetrics = metrics;
        this.perfLoading = false;
      },
      error => {
        this.message.error('获取Redis性能指标失败：' + error.message);
        this.perfLoading = false;
      }
    );
  }
  
  clearCache(pattern: string): void {
    if (!pattern) {
      this.message.warning('请输入要清除的缓存键模式');
      return;
    }
    
    this.isClearing = true;
    this.redisCacheService.clearCache(pattern).pipe(
      takeUntil(this.destroy$),
      finalize(() => {
        this.isClearing = false;
      })
    ).subscribe(
      result => {
        this.message.success(`已清除 ${result.count} 个缓存键：${result.message}`);
        this.loadRedisStatus(); // 刷新状态
      },
      error => {
        this.message.error('清除缓存失败：' + error.message);
      }
    );
  }
  
  measurePerformance(): void {
    this.isPerformanceTesting = true;
    this.loadPerformanceMetrics();
    this.isPerformanceTesting = false;
  }
  
  generateTestData(): void {
    this.isGeneratingData = true;
    this.redisCacheService.generateTestData().pipe(
      takeUntil(this.destroy$),
      finalize(() => {
        this.isGeneratingData = false;
      })
    ).subscribe(
      result => {
        this.message.success('已生成测试数据');
        this.loadRedisStatus();
      },
      error => {
        console.error('生成测试数据失败', error);
        this.message.error('生成测试数据失败: ' + error.message);
      }
    );
  }
  
  toggleAutoRefresh(): void {
    if (this.autoRefresh) {
      this.startAutoRefresh();
    } else {
      this.stopAutoRefresh();
    }
  }
  
  private startAutoRefresh(): void {
    this.stopAutoRefresh(); // 确保先停止已有的订阅
    
    // 创建定时刷新
    this.refreshSubscription = interval(this.refreshInterval * 1000).pipe(
      takeUntil(this.destroy$),
      switchMap(() => this.redisCacheService.getStatus())
    ).subscribe(
      status => {
        this.redisStatus = status;
        this.hitRatePercentage = this.redisCacheService.calculateHitRatePercentage(status);
        this.memoryUsagePercentage = this.redisCacheService.calculateMemoryUsagePercentage(status);
      },
      error => {
        console.error('自动刷新Redis状态失败', error);
        this.message.error('自动刷新失败，已停止');
        this.autoRefresh = false;
        this.stopAutoRefresh();
      }
    );
  }
  
  private stopAutoRefresh(): void {
    if (this.refreshSubscription) {
      this.refreshSubscription.unsubscribe();
      this.refreshSubscription = null;
    }
  }
} 